<?php

use Common\Service\DataService;

/** 发送邮件
 * @param $to string
 * @param $title string
 * @param $content string
 * @return bool
 * */
function sendMail($to, $title, $content) {
    Vendor('PHPMailer.PHPMailerAutoload');
    $mail = new PHPMailer(); //实例化
    $mail->IsSMTP(); // 启用SMTP
    $mail->Host = sysconf('email_smtp'); //smtp服务器的名称（这里以QQ邮箱为例）
    //QQ邮箱开启SSL
    $mail->SMTPSecure = TRUE; //开启ssl
    $mail->Port = sysconf('email_port'); //端口号
    $mail->SMTPAuth = TRUE; //启用smtp认证
    $mail->Username = sysconf('email_username'); //发件人邮箱名
    $mail->Password = sysconf('email_password'); //163邮箱发件人授权密码
    $mail->From = sysconf('email_username'); //发件人地址（也就是你的邮箱地址）
    $mail->FromName = sysconf('email_formname'); //发件人姓名
    $mail->AddAddress($to);
    $mail->WordWrap = 50; //设置每行字符长度
    $mail->IsHTML(TRUE); // 是否HTML格式邮件
    $mail->CharSet = 'utf-8'; //设置邮件编码
    $mail->Subject = $title; //邮件主题
    $mail->Body = $content; //邮件内容
    $mail->AltBody = "这是一个纯文本的身体在非营利的HTML电子邮件客户端"; //邮件正文不支持HTML的备用显示
    if ($mail->Send()) {
        return true;
    } else {
        return $mail->ErrorInfo;
    }
}

/**
 * curl工具
 * @param type $url
 * @param type $data
 * @return type
 */
function http($url, $data = null) {
    $curl = curl_init(); //初始化
    curl_setopt($curl, CURLOPT_URL, $url); //设置cURL传输选项
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE); //设置cURL传输选项
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE); //设置cURL传输选项
    if (!empty($data)) {
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
    }
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    $output = curl_exec($curl); //执行
    curl_close($curl); //关闭
    return $output;
}

/**
 * description: 递归菜单
 * @param unknown $array
 * @param number $fid
 * @param number $level
 * @param number $type 1:顺序菜单 2树状菜单
 * @return multitype:number
 */
function get_column($array, $type = 1, $fid = 0, $level = 0) {
    $column = array();
    if ($type == 2) {
        foreach ($array as $key => $vo) {
            if ($vo['pid'] == $fid) {
                $vo['level'] = $level;
                $column[$key] = $vo;
                $column [$key][$vo['id']] = get_column($array, $type = 2, $vo['id'], $level + 1);
            }
        }
    } else {
        foreach ($array as $key => $vo) {
            if ($vo['pid'] == $fid) {
                $vo['level'] = $level;
                $column[] = $vo;
                $column = array_merge($column, get_column($array, $type = 1, $vo['id'], $level + 1));
            }
        }
    }

    return $column;
}

/**
 * 获取ip
 * @return type
 */
function getIp() {
    if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown"))
        $ip = getenv("HTTP_CLIENT_IP");
    else
    if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown"))
        $ip = getenv("HTTP_X_FORWARDED_FOR");
    else
    if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown"))
        $ip = getenv("REMOTE_ADDR");
    else
    if (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown"))
        $ip = $_SERVER['REMOTE_ADDR'];
    else
        $ip = "unknown";
    return ($ip);
}

/**
 * 判断手机号
 * @param type $text 手机号
 * @return type 
 */
function is_mobile($text) {
    $search = '/^0?1[3|4|5|6|7|8][0-9]\d{8}$/';
    if (preg_match($search, $text)) {
        return ( true );
    } else {
        return ( false );
    }
}

//判断是否是正确的邮箱格式;  
function is_email($email) {
    $mode = '/\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/';
    if (preg_match($mode, $email)) {
        return true;
    } else {
        return false;
    }
}

// 检测输入的验证码是否正确，$code为用户输入的验证码字符串
function check_verify($code, $id = '') {
    $verify = new \Think\Verify();
    return $verify->check($code, $id);
}

/*
 * 加密解密函数
 * $string:要加密的字符串
 * $operation：E=》加密，D=》解密
 * $key：密匙
 */

function encrypt($string, $operation, $key = '') {
    $key = md5($key);
    $key_length = strlen($key);
    $string = $operation == 'D' ? base64_decode(str_replace(array('-', '*'), array('/', '+'), $string)) : substr(md5($string . $key), 0, 8) . $string;
    $string_length = strlen($string);
    $rndkey = $box = array();
    $result = '';
    for ($i = 0; $i <= 255; $i++) {
        $rndkey[$i] = ord($key[$i % $key_length]);
        $box[$i] = $i;
    }
    for ($j = $i = 0; $i < 256; $i++) {
        $j = ($j + $box[$i] + $rndkey[$i]) % 256;
        $tmp = $box[$i];
        $box[$i] = $box[$j];
        $box[$j] = $tmp;
    }
    for ($a = $j = $i = 0; $i < $string_length; $i++) {
        $a = ($a + 1) % 256;
        $j = ($j + $box[$a]) % 256;
        $tmp = $box[$a];
        $box[$a] = $box[$j];
        $box[$j] = $tmp;
        $result.=chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
    }
    if ($operation == 'D') {
        if (substr($result, 0, 8) == substr(md5(substr($result, 8) . $key), 0, 8)) {
            return substr($result, 8);
        } else {
            return '';
        }
    } else {
        return str_replace(array('=', '/', '+'), array('', '-', '*'), base64_encode($result));
    }
}

/**
 * 设备或配置系统参数
 * @param string $name 参数名称
 * @param bool $value 默认是null为获取值，否则为更新
 * @return string|bool
 * @throws \think\Exception
 * @throws \think\exception\PDOException
 */
function sysconf($field, $value = null) {
    $config = array();
    $table = M('adminConfig');
    if ($value !== null) {
        list($config, $data) = array(array(), array('field' => $field, 'value' => $value));
        return DataService::save($table, $data, 'field');
    }
    if (empty($config)) {
        $config = $table->where(array('field' => $field))->find();
    }
    return isset($config['value']) ? $config['value'] : '';
}

//获取配置字段
function sysconf1($field) {
    if (!$field) {
        return;
    }
    $config = M('admin_config');
    $config_info = $config->where(array('field' => $field))->find();
    if (!$config_info) {
        return;
    } else {
        return $config_info['value'];
    }
}

/**
 * 密码加密
 * @param type $string
 * @return type
 */
function encryption($string) {
    return md5(sha1(sha1(md5(sha1($string)))));
}

/**
 * array_column 函数兼容
 */
if (!function_exists("array_column")) {

    function array_column(array &$rows, $column_key, $index_key = null) {
        $data = array();
        foreach ($rows as $row) {
            if (empty($index_key)) {
                $data[] = $row[$column_key];
            } else {
                $data[$row[$index_key]] = $row[$column_key];
            }
        }
        return $data;
    }

}

//将内容进行UNICODE编码，编码后的内容格式：\u56fe\u7247 （原始：图片）  
function unicode_encode($name) {
    $name = iconv('UTF-8', 'UCS-2', $name);
    $len = strlen($name);
    $str = '';
    for ($i = 0; $i < $len - 1; $i = $i + 2) {
        $c = $name[$i];
        $c2 = $name[$i + 1];
        if (ord($c) > 0) {    // 两个字节的文字  
            $str .= '\u' . base_convert(ord($c), 10, 16) . base_convert(ord($c2), 10, 16);
        } else {
            $str .= $c2;
        }
    }
    return $str;
}

/**
 * 设置上传文件子目录
 * @param type $name
 * @return type
 */
function upload_path($name) {
    return $name;
}

/**
 * 获取http类型
 * @return type
 */
function http_type() {
    return ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' : 'http://';
}

function getDomain() {
    return http_type() . $_SERVER['HTTP_HOST'];
}

/**
 * 计算几分钟前、几小时前、几天前、几月前、几年前。
 * $agoTime string Unix时间
 * @author tangxinzhuan
 * @version 2016-10-28
 */
function time_ago($agoTime) {
    $agoTime = (int) $agoTime;

    // 计算出当前日期时间到之前的日期时间的毫秒数，以便进行下一步的计算
    $time = time() - $agoTime;

    if ($time >= 31104000) { // N年前
        $num = (int) ($time / 31104000);
        return $num . '年前';
    }
    if ($time >= 2592000) { // N月前
        $num = (int) ($time / 2592000);
        return $num . '月前';
    }
    if ($time >= 86400) { // N天前
        $num = (int) ($time / 86400);
        return $num . '天前';
    }
    if ($time >= 3600) { // N小时前
        $num = (int) ($time / 3600);
        return $num . '小时前';
    }
    if ($time > 60) { // N分钟前
        $num = (int) ($time / 60);
        return $num . '分钟前';
    }
    if ($time < 60) {
        return $time . '秒前';
    }
    return '1分钟前';
}
